<?php
/*
 * CRequest  处理类
 * @author andery <andery@foxmail.com>
 * @link http://www.minophp.com/
 * @version $Id: CRequest.lib.php 2010-08-22 20:14:43Z andery $
 */
class CRequest
{
    public static function socket_request($url, $post = '', $cookie = '', $timeout = 15, $block = true)
    {
        $matches = parse_url($url);
        $host = $matches['host'];
        $path = isset($matches['path']) ? $matches['path'].(isset($matches['query']) ? '?'.$matches['query'] : '') : '/';
        $port = isset($matches['port']) ? $matches['port'] : 80;
        if ($post) {
            $out = "POST $path HTTP/1.0\r\n";
            $out .= "Accept: */*\r\n";
            $out .= "Accept-Language: zh-cn\r\n";
            $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
            $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
            $out .= "Host: $host\r\n";
            $out .= 'Content-Length: '.strlen($post)."\r\n";
            $out .= "Connection: Close\r\n";
            $out .= "Cache-Control: no-cache\r\n";
            $out .= "Cookie: $cookie\r\n\r\n";
            $out .= $post;
        } else {
            $out = "GET $path HTTP/1.0\r\n";
            $out .= "Accept: */*\r\n";
            $out .= "Accept-Language: zh-cn\r\n";
            $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
            $out .= "Host: $host\r\n";
            $out .= "Connection: Close\r\n";
            $out .= "Cookie: $cookie\r\n\r\n";
        }
        $fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
        if(!$fp) {
            return '';
        }
        stream_set_blocking($fp, $block);
        stream_set_timeout($fp, $timeout);
        @fwrite($fp, $out);
        $status = stream_get_meta_data($fp);
        $data = '';
        if(!$status['timed_out']) {
            while(!feof($fp)) {
                $data .= fread($fp, 8192);
            }
        }
        @fclose($fp);
        return $data;
    }
    
    public static function curl_request($url, $post='')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        $data = curl_exec($ch); 
        curl_close($ch);
        return $data;
    }
}